/*
  Name: DeadProxyClientSendHandler.cpp
  Copyright:
  Author: Carl Chatfield
  Date: 19/01/08 21:26
  Description: Queues Packets to be sent to prevent spamming the game server
*/


#include "DeadProxyClientSendQueue.h"


SendQueue::SendQueue(PacketQueue * Que, wxCondition * SendCond, wxCondition * PacketCond, SOCKET ToServSock)
{
    Queue = Que;
    SendCondition = SendCond;
    ToServerSocket = ToServSock;
    PacketCondition = PacketCond;
}

void* SendQueue::Entry()
{
    unsigned long long int LastSendTime;
    int ToSend = 0;
    int nResult = 0;
    PacketBuffer * packet;
    while(true)
    {
        SendCondition->Wait();
        if(ToSend == 0) //If weve finished sending a packet get a new one
        {
            delete packet; //Delete the old packet
            if(Queue->GetCount() == 0) // check if there is a packet available
            {
                PacketCondition->Wait(); // wait for a packet to arrive in the queue
            }
            packet = Queue->GetPacket(); //Get a new packet
            ToSend = packet->GetLength(); //Set the length of data to send to packet length
        } 
        while(true)
        {
            nResult = send(ToServerSocket, (char*)packet->GetBuffer(), ToSend, 0);
            if(nResult == SOCKET_ERROR)
            {
                if (WSAGetLastError() == WSAEWOULDBLOCK) //Check if the buffer is full
                {
                    break; //Break and wait for another Send() message to continue sending packet
                }
            }
            ToSend =- nResult; //How much data do we have left to send 
            if(ToSend == 0) //Check if we have sent all our data
            {
                break; //Break and wait for another Send message, this time a new packet will be sent
            }
        }

    }
    return NULL;
}

void SendQueue::OnExit()
{
}
